package 二叉树.二叉搜索树中的搜索;

/**
 * @program: leet-code
 * @description: leetcode_700_二叉搜索树中的搜索
 * @author: Acerola
 * @create: 2022-10-01 10:41
 **/
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    //普通二叉树递归
    public TreeNode searchBST1(TreeNode root, int val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        //递归有返回值，因此需要接住返回值，否则递归了寂寞
        TreeNode treeNode = searchBST1(root.left, val);
        if (treeNode != null) {
            return treeNode;
        }

        return searchBST1(root.right, val);
    }

    //二叉搜索树递归
    public TreeNode searchBST2(TreeNode root, int val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        //递归有返回值，因此需要接住返回值，否则递归了寂寞
        if (val < root.val) {
            return searchBST2(root.left, val);
        } else {
            return searchBST2(root.right, val);
        }

    }
}
